package com.bsj.power.sdk.config.mq;

import com.bsj.power.common.config.rocketmq.constant.ConsumerGroupConstant;
import com.bsj.power.common.constant.MqTopicAndTagConstants;
import com.bsj.power.common.util.ExceptionUtil;
import com.bsj.power.sdk.service.handle.HKSdkHandle;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author yinhao
 * @version 1.0
 * @description 附件下载MQ接收消息
 * @date 2024/8/23
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = MqTopicAndTagConstants.SDK_FILE_SERVER_TOPIC,
        consumerGroup = ConsumerGroupConstant.TRAVEL_SDK_DOWN_MSG_GROUP,
        selectorExpression = MqTopicAndTagConstants.SDK_FILE_DOWNLOAD_TAG,
        messageModel = MessageModel.CLUSTERING)
public class MqttSDKFileRocketmqConsumer implements RocketMQListener<MessageExt>, RocketMQPushConsumerLifecycleListener {

    @Autowired
    private HKSdkHandle hkSdkHandle;

    @Async
    @Override
    public void onMessage(MessageExt ext) {
        String message = new String(ext.getBody());
        String tags = ext.getTags();
        log.info("附件SDK下载处理器MQ端消息消费,tag: {}, msg: {}", tags, message);
        try {
            hkSdkHandle.doPush(ext.getBody());
        } catch (Exception e) {
            log.error("作业管控系统MQ数据消费-->消费失败，失败原因： {}", ExceptionUtil.getStackStr(e));
        }
    }

    @Override
    public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {
        // 设置消费者消息重试次数
        defaultMQPushConsumer.setMaxReconsumeTimes(3);
        //设置实例名称
        defaultMQPushConsumer.setInstanceName(MqTopicAndTagConstants.MQTT_PROCESS_SDK_FILE_INSTANCE_NAME);
    }
}
